package cn.tianyigps.tianyigpsgatherchecker.dao;

import cn.tianyigps.tianyigpsgatherchecker.bean.EquipmentCheckModel;
import cn.tianyigps.tianyigpspublic.mongo.dao.BaseDaoImp;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;


/**
 * Created with IntelliJ IDEA
 * Created By CuiGuibin
 * Date: 2018/5/14
 * Time: 18:05
 * Description:
 */
@Repository("equipmentCheckModelDao")
@Slf4j
public class EquipmentCheckModelDaoImp extends BaseDaoImp<EquipmentCheckModel> implements EquipmentCheckModelDao {
    @Autowired
    MongoTemplate mongoTemplate;

    private String latestEquipmentData = "latestEquipmentData";

    @Override
    public EquipmentCheckModel getEquipmentCheckModelById(String equipmentId) {
        Criteria criteria = Criteria.where("equipmentId").is(equipmentId);
        Query query = new Query(criteria);
        return mongoTemplate.findOne(query, getClz(), latestEquipmentData);
    }

    //修改查询语句

    @Override
    public List<EquipmentCheckModel> getGather(Map<String, String> param) {
        Criteria criteria = Criteria.where("point")
                .near(new Point(Double.parseDouble(param.get("Longitude")),Double.parseDouble(param.get("Latitude"))))
                .maxDistance(Integer.parseInt(param.get("radius")))
                .and("lineStatusTime").lt(new DateTime().secondOfMinute().addToCopy(-Integer.parseInt(param.get("gatherTime"))));
        return mongoTemplate.find(new Query(criteria), getClz(), latestEquipmentData);
    }


    @Override
    public UpdateResult updateCheckStatus(String equipmentId, List<String> checkRuleList, String fieldName) {
        Query query = new Query();
        query.addCriteria(Criteria.where("equipmentId").is(equipmentId));
        Update update = new Update();
        update.set("checkStatusModel." + fieldName, checkRuleList);
        return mongoTemplate.upsert(query, update, EquipmentCheckModel.class, latestEquipmentData);
    }








}
